package org.jeecg.modules.demo.staffmanagement.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.jeecg.common.api.vo.Result;
import org.jeecg.common.aspect.annotation.AutoLog;
import org.jeecg.common.constant.CommonConstant;
import org.jeecg.common.exception.JeecgBootException;
import org.jeecg.common.system.base.controller.JeecgController;
import org.jeecg.common.system.query.QueryGenerator;
import org.jeecg.common.system.vo.LoginUser;
import org.jeecg.common.util.PasswordUtil;
import org.jeecg.common.util.TokenUtils;
import org.jeecg.common.util.oConvertUtils;
import org.jeecg.modules.demo.basestaffshareholder.service.IBaseStaffShareholderService;
import org.jeecg.modules.demo.basestaffshop.entity.BaseStaffShop;
import org.jeecg.modules.demo.basestaffshop.service.IBaseStaffShopService;
import org.jeecg.modules.demo.basestaffstatus.entity.BaseStaffStatus;
import org.jeecg.modules.demo.basestaffstatus.service.IBaseStaffStatusService;
import org.jeecg.modules.demo.commoditymanagement.entity.CommodityManagement;
import org.jeecg.modules.demo.commoditymanagement.service.ICommodityManagementService;
import org.jeecg.modules.demo.projectmanagement.entity.ProjectManagement;
import org.jeecg.modules.demo.projectmanagement.service.IProjectManagementService;
import org.jeecg.modules.demo.staffmanagement.entity.*;
import org.jeecg.modules.demo.staffmanagement.service.IStaffManagementService;
import org.jeecg.modules.demo.stockmanage.entity.StockManage;
import org.jeecg.modules.demo.stockmanage.service.IStockManageService;
import org.jeecg.modules.system.entity.SysUser;
import org.jeecg.modules.system.entity.SysUserRole;
import org.jeecg.modules.system.service.ISysUserRoleService;
import org.jeecg.modules.system.service.ISysUserService;
import org.jeecg.modules.util.DateUtils;
import org.jeecg.modules.util.RedisUtils;
import org.jeecg.modules.util.ToolsUtils;
import org.jeecgframework.poi.excel.def.NormalExcelConstants;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.view.JeecgEntityExcelView;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * 员工管理
 */
@Api(tags = "员工管理")
@RestController
@RequestMapping("/staffmanagement/staffManagement")
@Slf4j
public class StaffManagementController extends JeecgController<StaffManagement, IStaffManagementService> {
    @Autowired
    private IStaffManagementService staffManagementService;
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private IBaseStaffShareholderService baseStaffShareholderService;
    @Autowired
    private IBaseStaffShopService baseStaffShopService;
    @Autowired
    private IStockManageService stockManageService;
    @Autowired
    private ICommodityManagementService commodityManagementService;
    @Autowired
    private IProjectManagementService projectManagementService;
    @Autowired
    private IBaseStaffStatusService baseStaffStatusService;
    @Autowired
    private ISysUserRoleService sysUserRoleService;
    @Value("${jeecg.path.upload}")
    private String upLoadPath;

    /**
     * 分页列表查询
     */
    @AutoLog(value = "员工管理-分页列表查询")
    @ApiOperation(value = "员工管理-分页列表查询", notes = "员工管理-分页列表查询")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(StaffManagement staffManagement,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   @RequestParam(name = "startTime", defaultValue = "") String startTime,
                                   @RequestParam(name = "endTime", defaultValue = "") String endTime,
                                   HttpServletRequest req) throws ParseException {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }

        QueryWrapper<StaffManagement> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("store_id", storeId);
        QueryGenerator.initQueryWrapper(queryWrapper, staffManagement, req.getParameterMap());
        Map<String, String[]> map = req.getParameterMap();

        if (startTime.equals("")) {
            startTime = "2010-01-01";
        }
        if (endTime.equals("")) {
            endTime = "2050-01-01";
        }

        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
        Date startDate = simpleDateFormat.parse(startTime);
        Date endDate = simpleDateFormat.parse(endTime);
        Date nowDate = new Date();

        Page<StaffManagement> page = new Page<>(pageNo, pageSize);
        IPage<StaffManagement> pageList = staffManagementService.page(page, queryWrapper);
        List<StaffManagement> records = pageList.getRecords();
        String finalStartTime = startTime;
        String finalEndTime = endTime;
        records.forEach(sm -> {
            BaseStaffStatus bss = baseStaffStatusService.getById(sm.getEmployeeId());
            sm.setEmployee(bss.getStatusName());
            Double commoditySell = staffManagementService.getCommoditySell(sm.getId(), finalStartTime, finalEndTime);
            if (commoditySell == null) {
                commoditySell = 0.0;
            }
            Double projectSell = staffManagementService.getProjectSell(sm.getId(), finalStartTime, finalEndTime);
            if (projectSell == null) {
                projectSell = 0.0;
            }
            Double commodityMoney = staffManagementService.getCommodityMoney(sm.getId(), finalStartTime, finalEndTime);
            if (commodityMoney == null) {
                commodityMoney = 0.0;
            }
            Double projectMoney = staffManagementService.getProjectMoney(sm.getId(), finalStartTime, finalEndTime);
            if (projectMoney == null) {
                projectMoney = 0.0;
            }
            Double serveMoney = staffManagementService.getServeMoney(sm.getId(), finalStartTime, finalEndTime);
            if (serveMoney == null) {
                serveMoney = 0.0;
            }
            Double TotalShare = staffManagementService.getTotalShare(sm.getId(), finalStartTime, finalEndTime);
            if (TotalShare == null) {
                TotalShare = 0.0;
            }

            Date enterDate = sm.getEntryTime();
            Date salaryStartDate;
            Date salaryEndDate;
            if (startDate.before(enterDate)) {
                salaryStartDate = enterDate;
            } else {
                salaryStartDate = startDate;
            }

            if (endDate.after(nowDate)) {
                salaryEndDate = nowDate;
            } else {
                salaryEndDate = endDate;
            }
            int monthQty = DateUtils.getMonthQty(salaryStartDate, salaryEndDate);

            Double totalDeduction = ToolsUtils.doubleFormat(commodityMoney + projectMoney + serveMoney, 2);
            sm.setTotalSell(ToolsUtils.doubleFormat(commoditySell + projectSell, 2));
            sm.setSellMoney(ToolsUtils.doubleFormat(commodityMoney + projectMoney, 2));
            sm.setServeMoney(ToolsUtils.doubleFormat(serveMoney, 2));
            sm.setTotalDeduction(totalDeduction);
            sm.setTotalShare(ToolsUtils.doubleFormat(TotalShare, 2));
            Double totalSalary = sm.getBasePay() * monthQty + totalDeduction + TotalShare;
            sm.setTotalSalary(totalSalary);
        });

        return Result.OK(pageList);
    }

    /**
     * 查询员工列表-不分页，添加股东时查员工
     */
    @AutoLog(value = "查询员工列表-不分页")
    @ApiOperation(value = "查询员工列表-不分页", notes = "查询员工列表-不分页")
    @GetMapping(value = "/getStaffList")
    public Result<?> getStaffList(HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }

        List<StaffManagement> list = staffManagementService.list(new QueryWrapper<StaffManagement>().eq("store_id", storeId));
        return Result.OK(list);
    }

    /**
     * 查询销售提成明细
     */
    @AutoLog(value = "员工管理-查询销售提成明细")
    @ApiOperation(value = "员工管理-查询销售提成明细", notes = "员工管理-查询销售提成明细")
    @GetMapping(value = "/selectSaleDetail")
    public Result<?> selectSaleDetail(@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                      @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                      @RequestParam(name = "startTime", defaultValue = "") String startTime,
                                      @RequestParam(name = "endTime", defaultValue = "") String endTime,
                                      HttpServletRequest req) throws ParseException {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }
        //Map<String,String[]> map = req.getParameterMap();
        String orderCode = "";
        try {
            orderCode = req.getParameter("orderCode").replace("*", "");
        } catch (Exception ex) {
            orderCode = "";
        }
        String memberName = "";
        try {
            memberName = req.getParameter("memberName").replace("*", "");
        } catch (Exception ex) {
            memberName = "";
        }
        String staffName = "";
        try {
            staffName = req.getParameter("staffName").replace("*", "");
        } catch (Exception ex) {
            staffName = "";
        }
        String staffTel = "";
        try {
            staffTel = req.getParameter("staffTel").replace("*", "");
        } catch (Exception ex) {
            staffTel = "";
        }
        if (!startTime.trim().equals("")) {
            startTime = startTime + " 00:00:00";
        }
        if (!endTime.trim().equals("")) {
            endTime = endTime + " 23:59:59";
        }
        List<SaleDetail> listSaleDetail = staffManagementService.selectSaleDetail(orderCode, memberName, staffName, staffTel, startTime, endTime, storeId);
        IPage<SaleDetail> iPage = new Page<>(pageNo, pageSize);
        iPage.setRecords(listSaleDetail);
        return Result.OK(iPage);
    }

    /**
     * 查询服务提成明细
     */
    @AutoLog(value = "员工管理-查查询服务提成明细")
    @ApiOperation(value = "员工管理-查询服务提成明细", notes = "员工管理-查询服务提成明细")
    @GetMapping(value = "/selectServiceDetail")
    public Result<?> selectServiceDetail(@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                         @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                         @RequestParam(name = "startTime", defaultValue = "") String startTime,
                                         @RequestParam(name = "endTime", defaultValue = "") String endTime,
                                         HttpServletRequest req) throws ParseException {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }
        String orderCode = "";
        try {
            orderCode = req.getParameter("orderCode").replace("*", "");
        } catch (Exception ex) {
            orderCode = "";
        }
        String memberName = "";
        try {
            memberName = req.getParameter("memberName").replace("*", "");
        } catch (Exception ex) {
            memberName = "";
        }
        String staffName = "";
        try {
            staffName = req.getParameter("staffName").replace("*", "");
        } catch (Exception ex) {
            staffName = "";
        }
        String staffTel = "";
        try {
            staffTel = req.getParameter("staffTel").replace("*", "");
        } catch (Exception ex) {
            staffTel = "";
        }
        if (!startTime.trim().equals("")) {
            startTime = startTime + " 00:00:00";
        }
        if (!endTime.trim().equals("")) {
            endTime = endTime + " 23:59:59";
        }
        List<ServiceDetail> listServiceDetail = staffManagementService.selectServiceDetail(orderCode, memberName, staffName, staffTel, startTime, endTime, storeId);
        IPage<ServiceDetail> iPage = new Page<>(pageNo, pageSize);
        iPage.setRecords(listServiceDetail);
        return Result.OK(iPage);
    }

    /**
     * 查询管家分红明细
     */
    @AutoLog(value = "员工管理-查询管家分红明细")
    @ApiOperation(value = "员工管理-查询管家分红明细", notes = "员工管理-查询管家分红明细")
    @GetMapping(value = "/selectStaffShareDetail")
    public Result<?> selectStaffShareDetail(@RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                            @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                            @RequestParam(name = "startTime", defaultValue = "") String startTime,
                                            @RequestParam(name = "endTime", defaultValue = "") String endTime,
                                            HttpServletRequest req) throws ParseException {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }
        String orderCode = "";
        try {
            orderCode = req.getParameter("orderCode").replace("*", "");
        } catch (Exception ex) {
            orderCode = "";
        }
        String memberName = "";
        try {
            memberName = req.getParameter("memberName").replace("*", "");
        } catch (Exception ex) {
            memberName = "";
        }
        String staffName = "";
        try {
            staffName = req.getParameter("staffName").replace("*", "");
        } catch (Exception ex) {
            staffName = "";
        }
        String staffTel = "";
        try {
            staffTel = req.getParameter("staffTel").replace("*", "");
        } catch (Exception ex) {
            staffTel = "";
        }
        if (!startTime.trim().equals("")) {
            startTime = startTime + " 00:00:00";
        }
        if (!endTime.trim().equals("")) {
            endTime = endTime + " 23:59:59";
        }
        List<StaffShareDetail> listStaffShareDetail = staffManagementService.selectStaffShareDetail(orderCode, memberName, staffName, staffTel, startTime, endTime, storeId);
        IPage<StaffShareDetail> iPage = new Page<>(pageNo, pageSize);
        iPage.setRecords(listStaffShareDetail);
        return Result.OK(iPage);
    }

    /**
     * 懒得让前端改接口地址了，lists指向list方法
     */
    @AutoLog(value = "员工管理-分页列表查询")
    @ApiOperation(value = "员工管理-分页列表查询", notes = "员工管理-分页列表查询")
    @GetMapping(value = "/lists")
    public Result<?> queryPageLists(StaffManagement staffManagement,
                                    @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                    @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                    @RequestParam(name = "startTime", defaultValue = "") String startTime,
                                    @RequestParam(name = "endTime", defaultValue = "") String endTime,
                                    HttpServletRequest req) throws ParseException {
        return queryPageList(staffManagement, pageNo, pageSize, startTime, endTime, req);
    }

    //员工管理-通过id查询
    @AutoLog(value = "员工管理-通过id查询")
    @ApiOperation(value = "员工管理-分页列表查询", notes = "员工管理-分页列表查询")
    @GetMapping(value = "/queryOne")
    public Result<?> queryOne() {
        QueryWrapper<StaffManagement> queryWrapper = new QueryWrapper<>();
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        queryWrapper.eq("contact", sysUser.getUsername());
        StaffManagement data = staffManagementService.getOne(queryWrapper);
        return Result.OK(data);
    }

    //员工管理-获取商品列表
    @AutoLog(value = "员工管理-获取商品列表")
    @ApiOperation(value = "员工管理-获取商品列表", notes = "员工管理-获取商品列表")
    @GetMapping(value = "/shopList")
    public Result<?> shopList(@RequestParam(name = "staffId", required = true) String staffId,
                              @RequestParam(name = "search", required = false) String search) {
        QueryWrapper<BaseStaffShop> queryServe = new QueryWrapper<>();
        queryServe.eq("staff_id", staffId);
        if (oConvertUtils.isNotEmpty(search)) {
            queryServe.like("trade_name", search);
        }
        List<BaseStaffShop> pageList = baseStaffShopService.list(queryServe);
        return Result.OK(pageList);
    }

    //员工管理-获取股东列表
    @AutoLog(value = "员工管理-获取股东列表")
    @ApiOperation(value = "员工管理-获取股东列表", notes = "员工管理-获取股东列表")
    @GetMapping(value = "/ShareholderServiceList")
    public Result<?> ShareholderServiceList(@RequestParam(name = "staffId", required = true) String staffId
            , @RequestParam(name = "search", required = false) String search
            , HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }
        List<StockManage> list = stockManageService.list(new QueryWrapper<StockManage>()
                .eq("store_id", storeId)
                .eq("shareholders_housekeeper_id", staffId)
                .like(StringUtils.isNotEmpty(search), "stock_name", search));
        return Result.OK(list);
    }

    //员工管理-商品或项目
    @AutoLog(value = "员工管理-商品或项目")
    @ApiOperation(value = "员工管理-商品或项目", notes = "员工管理-商品或项目")
    @GetMapping(value = "/queryShopJob")
    public Result<?> queryShopJob(@RequestParam(name = "search", required = false) String search, HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }

        List<ShopJob> shopJob = new ArrayList<>();


        QueryWrapper<CommodityManagement> query1 = new QueryWrapper<>();
        query1.eq("store_id", storeId);
        if (oConvertUtils.isNotEmpty(search))
            query1.like("stock_name", search);
        List<CommodityManagement> listData1 = commodityManagementService.list(query1);
        for (CommodityManagement bean : listData1) {
            ShopJob sj = new ShopJob();
            sj.setId(bean.getId());
            sj.setTradeName(bean.getTradeName());
            sj.setCommodityCode(String.valueOf(bean.getCommodityCode()));
            sj.setRoyalties(String.valueOf(bean.getGrossRate()));
            sj.setType("商品");
            shopJob.add(sj);
        }

        QueryWrapper<ProjectManagement> query2 = new QueryWrapper<>();
        query2.eq("store_id", storeId);
        if (oConvertUtils.isNotEmpty(search))
            query2.like("project_name", search);
        List<ProjectManagement> listData2 = projectManagementService.list(query2);
        for (ProjectManagement bean : listData2) {
            ShopJob sj = new ShopJob();
            sj.setId(bean.getId());
            sj.setTradeName(bean.getProjectName());
            sj.setCommodityCode(String.valueOf(bean.getProjectNum()));
            sj.setRoyalties(String.valueOf(bean.getGrossProfit()));
            sj.setType("项目");
            shopJob.add(sj);
        }
        return Result.OK(shopJob);
    }

    //员工管理-商品或项目
    @AutoLog(value = "员工管理-商品或项目")
    @ApiOperation(value = "员工管理-商品或项目", notes = "员工管理-商品或项目")
    @GetMapping(value = "/queryShopJobById")
    public Result<?> queryShopJobById(@RequestParam(name = "id", required = false) String id) {

        CommodityManagement bean1 = commodityManagementService.getById(id);
        if (bean1 != null) {
            ShopJob sj = new ShopJob();
            sj.setId(bean1.getId());
            sj.setTradeName(bean1.getTradeName());
            sj.setCommodityCode(String.valueOf(bean1.getCommodityCode()));
            sj.setRoyalties(String.valueOf(bean1.getGrossRate()));
            sj.setType("商品");
            return Result.OK(sj);
        }

        ProjectManagement bean2 = projectManagementService.getById(id);
        if (bean2 != null) {
            ShopJob sj = new ShopJob();
            sj.setId(bean2.getId());
            sj.setTradeName(bean2.getProjectName());
            sj.setCommodityCode(String.valueOf(bean2.getProjectNum()));
            sj.setRoyalties(String.valueOf(bean2.getGrossProfit()));
            sj.setType("项目");
            return Result.OK(sj);
        }
        return Result.OK("");
    }

    /**
     * 添加
     */
    @AutoLog(value = "员工管理-添加")
    @ApiOperation(value = "员工管理-添加", notes = "员工管理-添加")
    @PostMapping(value = "/add")
    @Transactional(rollbackFor = Exception.class)
    public Result<?> add(@RequestBody JSONObject obj, HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }

        JSONObject vo = obj.getJSONObject("staffManagement");
        StaffManagement staffManagement = JSON.parseObject(vo.toJSONString(), StaffManagement.class);
        JSONArray staffStockholder = obj.getJSONArray("staffStockholder");

        // TODO 店铺管理员 才有权限添加 店员

        //联系方式 为账号
        String phone = staffManagement.getContact();
        if (oConvertUtils.isEmpty(phone)) {
            return Result.error("请输入联系方式");
        }
        if (StringUtils.isEmpty(staffManagement.getEmployeeId())) {
            return Result.error("必须选择员工身份");
        }
        if (staffManagement.getManualDiscount() < 0) {
            return Result.error("手动折扣限额不能小于0");
        }
        if (staffManagement.getBasePay() < 0) {
            return Result.error("底薪不能小于0");
        }

        // 全部用户
        List<SysUser> list = sysUserService.list();
        long count = list.stream().filter(su -> su.getUsername().equals(phone)).count();
        if (count > 0) {
            return Result.error("已存在的联系方式");
        }
        SysUser user = new SysUser();
        user.setCreateTime(new Date());//设置创建时间
        user.setUsername(phone);
        user.setPassword("123456");
        user.setPhone(phone);
        user.setRealname(staffManagement.getName());
        user.setStoreId(storeId);
        String salt = oConvertUtils.randomGen(8);
        user.setSalt(salt);
        String passwordEncode = PasswordUtil.encrypt(user.getUsername(), user.getPassword(), salt);
        user.setPassword(passwordEncode);
        user.setStatus(1);
        user.setDelFlag(CommonConstant.DEL_FLAG_0);

        // 生成店员账号
        BaseStaffStatus bss = baseStaffStatusService.getById(staffManagement.getEmployeeId());
        sysUserService.saveUser(user, bss.getRoleId(), "");

        staffManagement.setSellMoney(0.00);
        staffManagement.setServeMoney(0.00);
        staffManagement.setTotalDeduction(0.00);
        staffManagement.setTotalShare(0.00);
        staffManagement.setTotalSalary(0.00);
        staffManagement.setTotalSell(0.00);
        staffManagement.setStoreId(storeId);
        staffManagement.setUserId(user.getId());
        staffManagementService.save(staffManagement);

        // 关联股东
        for (int i = 0; i < staffStockholder.size(); i++) {
            JSONObject json = staffStockholder.getJSONObject(i);
            StockManage stockManage = new StockManage();
            stockManage.setId(json.getString("id"));
            stockManage.setShareholdersHousekeeperId(staffManagement.getId());
            stockManage.setMemberRatio(json.getDouble("memberRatio"));
            stockManage.setShareholdersRatio(json.getDouble("shareholdersRatio"));
            stockManageService.updateById(stockManage);
        }

        return Result.OK(staffManagement.getId());
    }

    /**
     * 编辑
     */
    @AutoLog(value = "员工管理-编辑")
    @ApiOperation(value = "员工管理-编辑", notes = "员工管理-编辑")
    @PutMapping(value = "/edit")
    @Transactional(rollbackFor = Exception.class)
    public Result<?> edit(@RequestBody JSONObject obj, HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }

        JSONObject vo = obj.getJSONObject("staffManagement");
        StaffManagement staffManagement = JSON.parseObject(vo.toJSONString(), StaffManagement.class);
        JSONArray staffStockholder = obj.getJSONArray("staffStockholder");

        // TODO 店铺管理员 才有权限编辑 店员

        //联系方式 为账号
        String phone = staffManagement.getContact();
        if (oConvertUtils.isEmpty(phone)) {
            return Result.error("请输入联系方式");
        }
        if (StringUtils.isEmpty(staffManagement.getEmployeeId())) {
            return Result.error("必须选择员工身份");
        }
        if (staffManagement.getManualDiscount() < 0) {
            return Result.error("手动折扣限额不能小于0");
        }
        if (staffManagement.getBasePay() < 0) {
            return Result.error("底薪不能小于0");
        }

        // 全部用户（除自己）
        List<SysUser> list = sysUserService.list(new QueryWrapper<SysUser>().ne("username", phone));
        long count = list.stream().filter(su -> su.getUsername().equals(phone)).count();
        if (count > 0) {
            return Result.error("已存在的联系方式");
        }

        // 更新用户手机号
        StaffManagement byId = staffManagementService.getById(staffManagement.getId());
        SysUser user = new SysUser();
        user.setId(byId.getUserId());
        user.setUsername(phone);
        sysUserService.updateById(user);

        // 更新用户身份
        sysUserRoleService.remove(new QueryWrapper<SysUserRole>().eq("user_id", byId.getUserId()));
        BaseStaffStatus bss = baseStaffStatusService.getById(staffManagement.getEmployeeId());
        sysUserRoleService.save(new SysUserRole().setUserId(byId.getUserId()).setRoleId(bss.getRoleId()));

        // 更新员工
        staffManagementService.updateById(staffManagement);

        // 先清空该员工关联的股东
//        stockManageService.update(new StockManage().setShareholdersHousekeeperId("").setShareholdersHousekeeper("")
//                , new QueryWrapper<StockManage>().eq("shareholders_housekeeper_id", staffManagement.getId()));
        stockManageService.deleteHouseKeeper(staffManagement.getId());
        // 再重新关联股东
        for (int i = 0; i < staffStockholder.size(); i++) {
            JSONObject json = staffStockholder.getJSONObject(i);
            StockManage stockManage = new StockManage();
            stockManage.setId(json.getString("id"));
            stockManage.setShareholdersHousekeeperId(staffManagement.getId());
            stockManage.setMemberRatio(json.getDouble("memberRatio"));
            stockManage.setShareholdersRatio(json.getDouble("shareholdersRatio"));
            stockManageService.updateById(stockManage);
        }

        return Result.OK(staffManagement.getId());
    }

    /**
     * 编辑（应该没用）
     */
    @AutoLog(value = "员工管理-编辑")
    @ApiOperation(value = "员工管理-编辑", notes = "员工管理-编辑")
    @PutMapping(value = "/edits")
    @Transactional(rollbackFor = JeecgBootException.class)
    public Result<?> edits(@RequestBody StaffManagement staffManagement, HttpServletRequest req) {
        String token = TokenUtils.getTokenByRequest(req);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);
        if (oConvertUtils.isEmpty(storeId)) {
            return Result.error("请先到首页选择店铺");
        }
        if (storeId.contains("过期")) {
            return Result.error("店铺已过期，续费后才可操作");
        }
        LoginUser sysUser = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        String username = staffManagement.getContact();
        String password = "123456";
        if (oConvertUtils.isEmpty(username)) {
            return Result.error("请输入联系方式");
        }

        LambdaQueryWrapper<SysUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysUser::getUsername, username);
        SysUser userv = sysUserService.getOne(queryWrapper);
        if (userv == null) {
            SysUser user = new SysUser();
            user.setCreateTime(new Date());//设置创建时间
            user.setUsername(username);
            user.setPassword(password);
            user.setRealname(staffManagement.getName());
            user.setStoreId(storeId);
            String salt = oConvertUtils.randomGen(8);
            user.setSalt(salt);
            String passwordEncode = PasswordUtil.encrypt(user.getUsername(), user.getPassword(), salt);
            user.setPassword(passwordEncode);
            user.setStatus(1);
            user.setDelFlag(CommonConstant.DEL_FLAG_0);
            //生成店员账号
            sysUserService.saveUser(user, "1484029105596477441", "");
            staffManagement.setStoreId(storeId);
        }
        staffManagementService.updateById(staffManagement);
        return Result.OK("编辑成功!");
    }


    /**
     * 通过id删除
     */
    @AutoLog(value = "员工管理-通过id删除")
    @ApiOperation(value = "员工管理-通过id删除", notes = "员工管理-通过id删除")
    @DeleteMapping(value = "/delete")
    public Result<?> delete(@RequestParam(name = "id", required = true) String id) {
        stockManageService.deleteHouseKeeper(id);
//        baseStaffShareholderService.deleteByStaffId(id);
        staffManagementService.removeById(id);
        return Result.OK("删除成功!");
    }

    /**
     * 批量删除
     */
    @AutoLog(value = "员工管理-批量删除")
    @ApiOperation(value = "员工管理-批量删除", notes = "员工管理-批量删除")
    @DeleteMapping(value = "/deleteBatch")
    public Result<?> deleteBatch(@RequestParam(name = "ids", required = true) String ids) {
        //this.staffManagementService.removeByIds(Arrays.asList(ids.split(",")));
        //return Result.OK("批量删除成功!");
        return Result.error("平台暂不支持批量删除");
    }

    /**
     * 重置密码
     */
    @AutoLog(value = "员工管理-重置密码")
    @ApiOperation(value = "员工管理-重置密码", notes = "员工管理-重置密码")
    @PutMapping(value = "/resetPassword")
    public Result<?> resetPassword(@RequestParam(name = "id", required = true) String id) {
        StaffManagement staff = staffManagementService.getById(id);
        SysUser user = sysUserService.getById(staff.getUserId());
        String salt = oConvertUtils.randomGen(8);
        user.setSalt(salt);
        String passwordEncode = PasswordUtil.encrypt(user.getUsername(), "123456", salt);
        user.setPassword(passwordEncode);
        sysUserService.updateById(user);
        return Result.OK("重置密码成功!");
    }

    /**
     * 通过id查询
     */
    @AutoLog(value = "员工管理-通过id查询")
    @ApiOperation(value = "员工管理-通过id查询", notes = "员工管理-通过id查询")
    @GetMapping(value = "/queryById")
    public Result<?> queryById(@RequestParam(name = "id", required = true) String id) {
        StaffManagement staffManagement = staffManagementService.getById(id);
        if (staffManagement == null) {
            return Result.error("未找到对应数据");
        }
        return Result.OK(staffManagement);
    }

    /**
     * 导出excel
     */
    @RequestMapping(value = "/exportXls")
    public ModelAndView exportXls(HttpServletRequest request, StaffManagement staffManagement) {
        //return super.exportXls(request, staffManagement, StaffManagement.class, "员工管理");
        String token = TokenUtils.getTokenByRequest(request);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);

        // Step.1 组装查询条件
        QueryWrapper<StaffManagement> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("store_id", storeId);
        QueryGenerator.initQueryWrapper(queryWrapper, staffManagement, request.getParameterMap());
        //Step.2 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        //update-end--Author:kangxiaolin  Date:20180825 for：[03]用户导出，如果选择数据则只导出相关数据----------------------
        List<StaffManagement> pageList = staffManagementService.list(queryWrapper);

        // Step.3 AutoPoi 导出Excel
        mv.addObject(NormalExcelConstants.FILE_NAME, "员工管理"); //此处设置的filename无效 ,前端会重更新设置一下
        mv.addObject(NormalExcelConstants.CLASS, StaffManagement.class);
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        //update-begin--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置--------------------
        ExportParams exportParams = new ExportParams("员工管理数据", "导出人:" + user.getRealname(), "员工管理");
        exportParams.setImageBasePath(upLoadPath);
        //update-end--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置----------------------
        mv.addObject(NormalExcelConstants.PARAMS, exportParams);
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 导出销售提成excel
     */
    @RequestMapping(value = "/exportXstcXls")
    public ModelAndView exportXstcXls(HttpServletRequest request, SaleDetail saleDetail) {
        //return super.exportXls(request, staffManagement, StaffManagement.class, "员工管理");
        String token = TokenUtils.getTokenByRequest(request);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);

        // Step.1 组装查询条件
        QueryWrapper<SaleDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("store_id", storeId);
        QueryGenerator.initQueryWrapper(queryWrapper, saleDetail, request.getParameterMap());
        //Step.2 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        //update-end--Author:kangxiaolin  Date:20180825 for：[03]用户导出，如果选择数据则只导出相关数据----------------------
        List<SaleDetail> pageList = staffManagementService.selectSaleDetail("", "", "", "", "", "", storeId);

        // Step.3 AutoPoi 导出Excel
        mv.addObject(NormalExcelConstants.FILE_NAME, "销售提成"); //此处设置的filename无效 ,前端会重更新设置一下
        mv.addObject(NormalExcelConstants.CLASS, SaleDetail.class);
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        //update-begin--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置--------------------
        ExportParams exportParams = new ExportParams("销售提成数据", "导出人:" + user.getRealname(), "销售提成");
        exportParams.setImageBasePath(upLoadPath);
        //update-end--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置----------------------
        mv.addObject(NormalExcelConstants.PARAMS, exportParams);
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 导出服务提成excel
     */
    @RequestMapping(value = "/exportFwtcXls")
    public ModelAndView exportFwtcXls(HttpServletRequest request, ServiceDetail serviceDetail) {
        //return super.exportXls(request, staffManagement, StaffManagement.class, "员工管理");
        String token = TokenUtils.getTokenByRequest(request);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);

        // Step.1 组装查询条件
        QueryWrapper<ServiceDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("store_id", storeId);
        QueryGenerator.initQueryWrapper(queryWrapper, serviceDetail, request.getParameterMap());
        //Step.2 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        //update-end--Author:kangxiaolin  Date:20180825 for：[03]用户导出，如果选择数据则只导出相关数据----------------------
        List<ServiceDetail> pageList = staffManagementService.selectServiceDetail("", "", "", "", "", "", storeId);

        // Step.3 AutoPoi 导出Excel
        mv.addObject(NormalExcelConstants.FILE_NAME, "服务提成"); //此处设置的filename无效 ,前端会重更新设置一下
        mv.addObject(NormalExcelConstants.CLASS, ServiceDetail.class);
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        //update-begin--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置--------------------
        ExportParams exportParams = new ExportParams("服务提成数据", "导出人:" + user.getRealname(), "服务提成");
        exportParams.setImageBasePath(upLoadPath);
        //update-end--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置----------------------
        mv.addObject(NormalExcelConstants.PARAMS, exportParams);
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 导出管家分红excel
     */
    @RequestMapping(value = "/exportGjfhXls")
    public ModelAndView exportFwtcXls(HttpServletRequest request, StaffShareDetail staffShareDetail) {
        //return super.exportXls(request, staffManagement, StaffManagement.class, "员工管理");
        String token = TokenUtils.getTokenByRequest(request);
        String storeId = (String) redisUtils.get(RedisUtils.storeId + token);

        // Step.1 组装查询条件
        QueryWrapper<StaffShareDetail> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("store_id", storeId);
        QueryGenerator.initQueryWrapper(queryWrapper, staffShareDetail, request.getParameterMap());
        //Step.2 AutoPoi 导出Excel
        ModelAndView mv = new ModelAndView(new JeecgEntityExcelView());
        //update-end--Author:kangxiaolin  Date:20180825 for：[03]用户导出，如果选择数据则只导出相关数据----------------------
        List<StaffShareDetail> pageList = staffManagementService.selectStaffShareDetail("", "", "", "", "", "", storeId);

        // Step.3 AutoPoi 导出Excel
        mv.addObject(NormalExcelConstants.FILE_NAME, "管家分红"); //此处设置的filename无效 ,前端会重更新设置一下
        mv.addObject(NormalExcelConstants.CLASS, StaffShareDetail.class);
        LoginUser user = (LoginUser) SecurityUtils.getSubject().getPrincipal();
        //update-begin--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置--------------------
        ExportParams exportParams = new ExportParams("管家分红数据", "导出人:" + user.getRealname(), "管家分红");
        exportParams.setImageBasePath(upLoadPath);
        //update-end--Author:liusq  Date:20210126 for：图片导出报错，ImageBasePath未设置----------------------
        mv.addObject(NormalExcelConstants.PARAMS, exportParams);
        mv.addObject(NormalExcelConstants.DATA_LIST, pageList);
        return mv;
    }

    /**
     * 通过excel导入数据
     */
    @RequestMapping(value = "/importExcel", method = RequestMethod.POST)
    public Result<?> importExcel(HttpServletRequest request, HttpServletResponse response) {
        return super.importExcel(request, response, StaffManagement.class);
    }

}
